package com.yanqu.road.server.manager.match;

import com.yanqu.road.entity.rank.cross.CrossUserRank;
import com.yanqu.road.logic.bussiness.rank.RankBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.helper.RankListHelper;
import com.yanqu.road.logic.pb.CrossRankPb;
import com.yanqu.road.pb.rank.RankProto;

import java.math.BigInteger;
import java.util.*;
import java.util.stream.IntStream;

/**
 * @author ：zfr
 * @date ：2021/3/17 15:38
 * 赛事每周排行
 */
public class MatchWeekRankModel {
    private int rankNum = GameConfig.RANK_DEFAULT_MAX_COUNT;
    private boolean isUpdate = false;
    private LinkedList<CrossUserRank> rankList;
    private long groupId;
    private int weekId;
    private RankProto.RankListMsg.Builder rankListMsg;

    public RankProto.RankListMsg.Builder getRankListMsg() {
        return rankListMsg;
    }

    public LinkedList<CrossUserRank> getRankList() {
        return rankList;
    }


    public MatchWeekRankModel(long groupId, int weekId) {
        rankList = new LinkedList<>();
        rankListMsg = RankProto.RankListMsg.newBuilder();
        this.groupId = groupId;
        this.weekId = weekId;
    }

    public long getGroupId() {
        return groupId;
    }

    public int getWeekId() {
        return weekId;
    }

    public void setRankList(LinkedList<CrossUserRank> userRankList) {
        synchronized (this) {
            rankList = new LinkedList<>(userRankList);
            RankListHelper.checkUserRankListValid(rankList);       //校验一下数组
            rankSort();
            while (rankList.size() > rankNum){
                rankList.removeLast();
            }
            initRankMsg();
        }
    }

    private void initRankMsg() {
        rankListMsg = CrossRankPb.parseRankListMsg(rankList);
    }

    public int getMyRank(long userId, long serverId) {
        synchronized (this) {
            OptionalInt result = IntStream.range(0, rankList.size()).filter(i -> rankList.get(i).getUserId() == userId &&
                    rankList.get(i).getUserBaseInfo().getServerId() == serverId).findFirst();
            if (result.isPresent()) {
                return result.getAsInt() + 1;
            }
            return -1;
        }
    }

    /**
     * 添加到排行
     */
    public void rankChange(CrossUserRank crossUserRank) {
        boolean isChange = false;
        synchronized (this) {
            int size = rankList.size();
            if (!rankList.stream().anyMatch(predicate -> predicate.getUserId() == crossUserRank.getUserId() &&
                    predicate.getUserBaseInfo().getServerId() == crossUserRank.getUserBaseInfo().getServerId())) {
                if (size < rankNum) {
                    CrossUserRank rank = crossUserRank.clone();
                    rank.setLastUpdateTime(System.currentTimeMillis() / 1000);
                    rankList.add(rank);
                    isChange = true;
                } else if (rankList.getLast().getValue().compareTo(crossUserRank.getValue()) < 0) {
                    CrossUserRank rank = rankList.getLast();
                    rank.setUserId(crossUserRank.getUserId());
                    rank.setUserBaseInfo(crossUserRank.getUserBaseInfo());
                    rank.setValue(crossUserRank.getValue());
                    rank.setLastUpdateTime(System.currentTimeMillis() / 1000);
                    rank.setParam(crossUserRank.getParam());
                    isChange = true;
                }
            } else {
                rankList.forEach(action -> {
                    if (action.getUserId() == crossUserRank.getUserId() && action.getUserBaseInfo().getServerId() == crossUserRank.getUserBaseInfo().getServerId()) {
                        action.setUserBaseInfo(crossUserRank.getUserBaseInfo());
                        action.setValue(crossUserRank.getValue());
                        action.setLastUpdateTime(System.currentTimeMillis() / 1000);
                        action.setParam(crossUserRank.getParam());
                    }
                });
                isChange = true;
            }
            if(isChange) {
                rankSort();
                initRankMsg();
                isUpdate = true;
            }
        }
    }

    private void rankSort() {
        rankList.sort(Comparator.comparing(CrossUserRank::getValue).reversed().thenComparing(CrossUserRank::getLastUpdateTime));
    }

    public void setRankNum(int rankNum) {
        this.rankNum = rankNum;
    }

    public void saveRankList() {
        LinkedList<CrossUserRank> newRankList;
        synchronized (this) {
            if (!isUpdate) {
                return;
            }
            newRankList = new LinkedList<>(rankList);
            isUpdate = false;
        }
        RankBussiness.updateCrossMatchWeekRankList(newRankList, groupId, weekId);
    }

    public LinkedList<CrossUserRank> removeRank(Set<Long> serverIdSet) {
        LinkedList<CrossUserRank> result = new LinkedList<>();
        synchronized (this) {
            Iterator<CrossUserRank> iterator = rankList.iterator();
            while(iterator.hasNext()){
                CrossUserRank rank = iterator.next();
                if(!serverIdSet.contains(rank.getUserBaseInfo().getServerId())){
                    if(rank.getValue().compareTo(BigInteger.ZERO) > 0) {
                        result.add(rank.clone());
                        rank.setValue(BigInteger.ZERO);
                        iterator.remove();    //策划需求要优化
                    }
                }
            }
            if(result.size() > 0) {
                rankSort();
                initRankMsg();
                isUpdate = true;
            }
        }
        return result;
    }
}
